package com.jju;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

import javax.swing.*;

public class MyChat extends JFrame implements ActionListener{
	private JTextArea jtaList,jtaInfo;
	private JLabel jlFirst,jlSecond,jlIp;
	private JTextField jtfIp;
	private JButton jb;
	private JPanel jp;
	
	private DatagramSocket ds;
	
	public MyChat(String title){
		super(title);
		try {
			ds=new DatagramSocket(8090);
		} catch (Exception e) {
			e.printStackTrace();
		}
		initCom();
	}
	
	private void initCom(){
		jtaList=new JTextArea(10,34);
		jtaInfo=new JTextArea(4,34);
		jlFirst=new JLabel("ChatRecords"+"                                                                                                    ");
		jlSecond=new JLabel("ToSendMessage"+"                                                                                               ");
		jlIp=new JLabel("IP");
		jtfIp=new JTextField(15);
		jb=new JButton("Send");
		
		jb.addActionListener(this);
		this.addWindowListener(new WindowAdapter(){
			@Override
			public void windowClosing(WindowEvent arg0) {
				super.windowClosing(arg0);
				ds.close();
			}
		});
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				byte[] buf = new byte[1024];
				DatagramPacket dpR = new DatagramPacket(buf, 1024);
				while (true) {
					try {
						ds.receive(dpR);
						jtaList.append("Form:" + dpR.getAddress() + "\n"
								+ new String(buf, 0, dpR.getLength()) + "\n");
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
		
		this.setLayout(new FlowLayout());
		this.add(jlFirst);
		this.add(jtaList);
		this.add(jlSecond);
		this.add(jtaInfo);
		this.add(jlIp);
		this.add(jtfIp);
		this.add(jb);
		
		this.setSize(400, 372);
		this.setVisible(true);
		this.setResizable(false);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		byte[] buf;
		buf=jtaInfo.getText().getBytes();
		try {
			DatagramPacket dpS=new DatagramPacket(buf,buf.length,InetAddress.getByName(jtfIp.getText()),8090);
			ds.send(dpS);
			jtaList.append("Me:"+jtaInfo.getText()+"\n");
			jtaInfo.setText("");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	public static void main(String[] args){
		new MyChat("MyChat");
	}
}
